package git_cmd

import (
	"context"
	"fmt"
	"os/exec"
	"strings"
	"time"

	"atomgit.com/openlinksaas/gitwrap/utils"
	"github.com/spf13/cobra"
)

var _ListLfsFile = &cobra.Command{
	Use: "listLfsFile",
	Run: func(cmd *cobra.Command, args []string) {
		ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
		defer cancel()

		cmdPath, err := exec.LookPath("git")
		if err != nil {
			utils.OutputError(err)
			return
		}

		gitCmd := exec.CommandContext(ctx, cmdPath, "lfs", "ls-files", "-n")
		gitCmd.Dir = gitFlagLocalPath
		resData, err := gitCmd.Output()
		if err != nil {
			ee, ok := err.(*exec.ExitError)
			if ok {
				utils.OutputError(fmt.Errorf(string(ee.Stderr)))
				return
			} else {
				utils.OutputError(err)
				return
			}
		}
		fileList := []string{}
		for _, line := range strings.Split(string(resData), "\n") {
			line = strings.Trim(line, " \r\n\t")
			if line == "" {
				continue
			}
			fileList = append(fileList, line)
		}
		utils.OutputData(fileList)
		return
	},
}
